package com.twu.biblioteca;

/**
 * Created with IntelliJ IDEA.
 * User: PREETHI
 * Date: 22/5/13
 * Time: 8:26 PM
 * To change this template use File | Settings | File Templates.
 */
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class framelogin {

    public JPanel loginPanel;
    JLabel label;
    JTextField textField;
    JPasswordField pwd;
    JButton submit;
    String loginId, password;
    userlist users;
    library lib;
    public framelogin(library lib)
    {
        loginPanel=new JPanel();
        users=new userlist();
        this.lib=lib;
    }
    public JPanel displayForm()
    {
        label=new JLabel("Login Id",JLabel.CENTER);
        textField=new JTextField(25);
        loginPanel.add(label);
        loginPanel.add(textField);
        label=new JLabel("Password");
        loginPanel.add(label);
        pwd=new JPasswordField(25);
        loginPanel.add(pwd);
        submit =new JButton("LOGIN");
        submit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(lib.getUsername() ==null)
                {
                     loginId=textField.getText();
                     password=pwd.getText();
                     if(! validateUsers(loginId,password))  {
                     JOptionPane.showMessageDialog(loginPanel,"Invalid Username or Password","Sorry",JOptionPane.INFORMATION_MESSAGE);

                         }
                    else
                     {
                     lib.setUsername(loginId);
                     JOptionPane.showMessageDialog(loginPanel,"You have successfully logged in","Success",JOptionPane.INFORMATION_MESSAGE);
                     }
                     textField.setText(" ");
                     pwd.setText("");

                }
                else
                    JOptionPane.showMessageDialog(loginPanel,"Invalid Option!","Invalid",JOptionPane.INFORMATION_MESSAGE);
            }
        });
        loginPanel.add(submit);
        loginPanel.setVisible(true);
        return loginPanel;

    }

    private boolean validateUsers(String username, String password) {

              if(users.loginInfo.containsKey(username))
              {
                  if(users.loginInfo.get(username).getPwd().equals(password))
                  {
                      return true;
                  }
              }
            return false;
    }
}
